package com.wish.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.base.dto.SaveJrFactoringDto;
import com.wish.base.entity.FkBusinessCredit;
import com.wish.base.entity.FkBusinessCreditSub;
import com.wish.base.entity.JrFactoring;
import com.wish.base.entity.JrFactoringDetail;
import com.wish.base.mapper.JrFactoringMapper;
import com.wish.base.service.IFkBusinessCreditService;
import com.wish.base.service.IFkBusinessCreditSubService;
import com.wish.base.service.IJrFactoringDetailService;
import com.wish.base.service.IJrFactoringService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.common.security.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 租约保理申请表 服务实现类
 * </p>
 *
 * @author group02
 * @since 2022-05-23
 */
@Service
public class JrFactoringServiceImpl extends ServiceImpl<JrFactoringMapper, JrFactoring> implements IJrFactoringService {
    @Autowired
    IFkBusinessCreditService iFkBusinessCreditService;

    @Autowired
    IFkBusinessCreditSubService iFkBusinessCreditSubService;

    @Autowired
    IJrFactoringDetailService iJrFactoringDetailService;

    //    @Autowired
//    IJrFactoringService iJrFactoringService;
    @Override
    public Integer saveFactoringApply(SaveJrFactoringDto saveJrFactoringDto) {
        long BusinessId = 0;
        List<JrFactoringDetail> factoringDetailList = saveJrFactoringDto.getFactoringDetailList();
        for (JrFactoringDetail jrFactoringDetail : factoringDetailList) {
            BusinessId= jrFactoringDetail.getBusinessId();
        }

        //查询风控表
        FkBusinessCredit business = iFkBusinessCreditService.getOne(new QueryWrapper<FkBusinessCredit>().eq("business_id", BusinessId));


        //判断是否授权
        if(business.getCreditStaus()==2){
            return 1;
        }

        BigDecimal hlOddCreditline = BigDecimal.ZERO;
        //查询风控主表  月度授信额度
        if(business.getHlMonthlyUsedCreditline()!=null&&!business.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)){
            hlOddCreditline=business.getHlMonthlyTotalCreditline().subtract(business.getHlMonthlyUsedCreditline());
        }else{
            hlOddCreditline=business.getHlMonthlyTotalCreditline();
        }
        //申请分期金额大于该商户中的该产品剩余授信金额
        if(saveJrFactoringDto.getRentMoney().compareTo(hlOddCreditline)==1){
            return 2;
        }
        //查询风控主表 年度授信额度
        BigDecimal oddCreditlineProduct = BigDecimal.ZERO;
        if(business.getHlUsedCreditline()!=null&& !business.getHlUsedCreditline().equals(BigDecimal.ZERO)){
            oddCreditlineProduct=business.getHlTotalCreditline().subtract(business.getHlUsedCreditline());
        }else{
            oddCreditlineProduct=business.getHlTotalCreditline();
        }
        //申请分期金额大于该商户中的该产品剩余授信金额
        if(saveJrFactoringDto.getRentMoney().compareTo(oddCreditlineProduct)==1){
            return 2;
        }

        //获取风控子表
        FkBusinessCreditSub product = iFkBusinessCreditSubService.getOne(new QueryWrapper<FkBusinessCreditSub>().eq("product_id", saveJrFactoringDto.getJrProductId()));

        //查询风控子表 月度授信额度
        BigDecimal subtractMonthly = BigDecimal.ZERO;
        if(product.getMonthlyUsedCreditline()!=null&&!product.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)){
            subtractMonthly=product.getMonthlyTotalCreditline().subtract(product.getMonthlyUsedCreditline());
        }else{
            subtractMonthly=product.getMonthlyTotalCreditline();
        }
        //申请分期金额大于该商户中的该产品剩余授信金额
        if(saveJrFactoringDto.getRentMoney().compareTo(subtractMonthly)==1){
            return 2;
        }
        //查询风控子表的 年度授信额度
        BigDecimal subtractProduct = BigDecimal.ZERO;
        if(product.getUsedCreditline()!=null&&!product.getUsedCreditline().equals(BigDecimal.ZERO)){
            subtractProduct=product.getTotalCreditline().subtract(product.getUsedCreditline());
        }else{
            subtractProduct=product.getTotalCreditline();
        }
        //申请分期金额大于该商户中的该产品剩余授信金额
        if(saveJrFactoringDto.getRentMoney().compareTo(subtractProduct)==1){
            return 2;
        }

        //风控表的额度 计算
        BigDecimal hlUsedCreditline1 = BigDecimal.ZERO;
        if(business.getHlUsedCreditline() != null && !business.getHlUsedCreditline().equals(BigDecimal.ZERO)) {
            hlUsedCreditline1 = business.getHlUsedCreditline().add(saveJrFactoringDto.getRentMoney());
        } else {
            hlUsedCreditline1 = saveJrFactoringDto.getRentMoney();
        }
        business.setHlUsedCreditline(hlUsedCreditline1);
        if(business.getHlMonthlyTotalCreditline() != null && !business.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if(business.getHlMonthlyUsedCreditline() != null && !business.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = business.getHlMonthlyUsedCreditline().add(saveJrFactoringDto.getRentMoney());
            } else {
                hlMonthlyUsedCreditline = saveJrFactoringDto.getRentMoney();
            }
            business.setHlMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }
        business.setUpdateTime(new Date());
        business.setUpdateUserid(SecurityUtils.getUserId());
        iFkBusinessCreditService.saveOrUpdate(business);

        //风控子表的额度 计算
        BigDecimal usedCreditlineProduct1 = BigDecimal.ZERO;

        //判断风控子表的总额度不为空
        if(product.getUsedCreditline() != null && !product.getUsedCreditline().equals(BigDecimal.ZERO)) {
            //数据库中的已经用额度加这次的额度
            usedCreditlineProduct1 = product.getUsedCreditline().add(saveJrFactoringDto.getRentMoney());
        } else {
            //直接赋值为这次的金额
            usedCreditlineProduct1 = saveJrFactoringDto.getRentMoney();
        }
        //赋值金额
        product.setUsedCreditline(usedCreditlineProduct1);
        //判断风控子表的月度额度不为空
        if(product.getMonthlyTotalCreditline() != null && !product.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if(product.getMonthlyUsedCreditline() != null && !product.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = product.getMonthlyUsedCreditline().add(saveJrFactoringDto.getRentMoney());
            } else {
                hlMonthlyUsedCreditline = saveJrFactoringDto.getRentMoney();
            }
            product.setMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }
        product.setUpdateTime(new Date());
        product.setUpdateUserid(SecurityUtils.getUserId());

        iFkBusinessCreditSubService.saveOrUpdate(product);

        //添加租约保理申请
        JrFactoring jrFactoring = new JrFactoring();
        BeanUtils.copyProperties(saveJrFactoringDto,jrFactoring);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        jrFactoring.setFactoringOrderNo("ZYBL"+simpleDateFormat.format(date));
        jrFactoring.setBusinessId(BusinessId+"");
        jrFactoring.setLoanAmount(jrFactoring.getFactoringCreditMoney());
        jrFactoring.setDelFlg(false);
        jrFactoring.setCreateTime(new Date());
        jrFactoring.setCreateUserid(SecurityUtils.getUserId());
        jrFactoring.setUpdateTime(new Date());
        jrFactoring.setUpdateUserid(SecurityUtils.getUserId());
        jrFactoring.setApplyState(1);

        boolean save = save(jrFactoring);
        // 保存保理明细
        List<JrFactoringDetail> factoringDetailList1 = saveJrFactoringDto.getFactoringDetailList();
        if (factoringDetailList1 != null) {
            for (JrFactoringDetail jrFactoringDetailEntity : factoringDetailList1) {
                // 保理申请ID
                jrFactoringDetailEntity.setFactoringId(jrFactoring.getId());
                jrFactoringDetailEntity.setBusinessId(BusinessId);
                // 公共信息
                jrFactoringDetailEntity.setDelFlg(false);
                jrFactoringDetailEntity.setCreateTime(new Date());
                jrFactoringDetailEntity.setCreateUserid(SecurityUtils.getUserId());
                jrFactoringDetailEntity.setUpdateTime(new Date());
                jrFactoringDetailEntity.setUpdateUserid(SecurityUtils.getUserId());
                iJrFactoringDetailService.save(jrFactoringDetailEntity);
//                // 冻结合同并且添加金融标识
//                CfContractEntity contract = cfContractMapper.selectById(jrFactoringDetailEntity.getCfContractId());
//                // 已冻结
//                contract.setFreezeStatus(FreezeStatusEnum.YDJ.getIndex());
//                // 租约保理
//                contract.setZyblFlg(true);
//                contract.setUpdateTime(nowTime);
//                contract.setUpdateUserid(saveJrFactoringDto.getLoginUserId());
//                cfContractMapper.updateById(contract);
//                // 更新出房合同上未收款的收款计划收款状态:未收款->冻结状态
//                RequestRemainingLeavingBill requestRemainingLeavingBill = new RequestRemainingLeavingBill();
//                requestRemainingLeavingBill.setContractId(jrFactoringDetailEntity.getCfContractId());
//                requestRemainingLeavingBill.setContractType(ContractTypeEnum.CF.getIndex());
//                requestRemainingLeavingBill.setSkStatus(SkStatusEnum.YDJ.getIndex());

            }
        }

        return 3;
    }
}
